package Easy;
//14.最长公共前缀
public class Solution14 {
    public String longestCommonPrefix(String[] strs) {
        String cop = new String();
        // 求最短length
        if (strs.length == 0)
            return "";
        if (strs.length == 1)
            return strs[0];
        int length = strs[0].length();
        if (length == 0) // 防止报错 先判断一次
            return "";
        for (int i = 0; i < strs.length - 1; i++) {
            if (length > strs[i + 1].length())
                length = strs[i + 1].length();
        }
        if (length == 0) // 如果所有字符串中有一个为空，则直接返回空
            return "";

        boolean b = true;
        int j;
        char[] chars = new char[strs.length];
        for (j = 0; j < length && b; j++) {
            chars[0] = strs[0].charAt(j);
            for (int i = 1; i < strs.length; i++) {
                chars[i] = strs[i].charAt(j);
                if (chars[i] != chars[i - 1]) {
                    b = false;
                    break;
                }
            }
        }
        j-=1;
        if(!b){
            j-=1;
        }
        cop = strs[0].substring(0, j + 1);

        return cop;
    }

    public static void main(String[] args) {
        Solution14 s = new Solution14();
        String[] strings = new String[]{"flower", "flow", "flight"};
        System.out.println(s.longestCommonPrefix(strings));
    }
}
